var refreshGirdData; // 更新数据
var companyId = '';
var departmentId = '';
var ztId = '';
var month;
var userdefault = {};
var params = {};

var headerCols = [];
var selectColumns = '';
var needSetActionTimeUserids = '';

var bootstrap = function ($, learun) {

    var pageWidth = 1024;
    var colNames = [];

    "use strict";
    var page = {
        init: function () {
            userdefault = learun.clientdata.get(['usersetting']);
            pageWidth = ($('.lr-layout-grid').width());

            page.bind();
        },
        bind: function () {
            // 搜索框初始化
            $('#txt_Keyword').on("keypress", function (e) {
                if (event.keyCode == "13") {
                    var $this = $(this);
                    var keyword = $this.val();
                    page.search({keyword: keyword});
                }
            });
            $('#company_select').lrselect({
                type: 'tree',
                // placeholder: '请选择机构',
                height: 300,
                maxHeight: 300,
                // 是否允许搜索
                //allowSearch: true,
                select: function (item) {
                    if (item && item.value != '-1') {
                        companyId = item.value;

                        $('#departmentId').lrselectRefresh({
                            // 访问数据接口地址
                            url: config.base_server() + 'departments/tree?access_token=' + config.getToken().access_token,
                            // 访问数据接口参数
                            param: {companyId: item.value, parentId: '0'},
                        });

                        $('#zt_select').lrselectRefresh({
                            // 访问数据接口地址
                            url: config.base_server() + 'gzzts/dropdownlist?access_token=' + config.getToken().access_token,
                            // 访问数据接口参数
                            param: {companyId: companyId},
                            select: function (ztItem) {
                                if (!ztItem || ztItem.value == '-1') {
                                    ztId = "";
                                } else {
                                    ztId = ztItem.value;

                                    page.initHeader();
                                    //加载默认款项
                                    $.ajax({
                                        url: config.base_server() + 'gzitementrys/findByZtId?ztId=' + ztId + '&access_token=' + config.getToken().access_token,
                                        type: "get",
                                        dataType: "json",
                                        success: function (result) {

                                            var _tempHeaderCols = jQuery.extend(true, [], headerCols);

                                            if (result.data != null) {
                                                selectColumns = result.data.columns; //所选列
                                                for (var i = 0; i < _tempHeaderCols.length; i++) {
                                                    if ((_tempHeaderCols[i].name != 'id' && _tempHeaderCols[i].name != 'departmentname' && _tempHeaderCols[i].name != 'usercode' && _tempHeaderCols[i].name != 'username') &&
                                                        result.data.columns.indexOf(_tempHeaderCols[i].label) < 0
                                                    ) {
                                                        _tempHeaderCols.splice(i, 1);
                                                        i--;
                                                    }
                                                }
                                            }

                                            page.initGrid(_tempHeaderCols);
                                            page.search();
                                        }
                                    });

                                }
                            }
                        }).lrselectSet(userdefault.ztId);

                    }
                }
            });
            $('#company_select').lrselectRefresh({
                // 访问数据接口地址
                url: config.base_server() + 'companys/tree?access_token=' + config.getToken().access_token,
                // 访问数据接口参数
                param: {parentId: '0'}
            }).lrselectSet(userdefault.companyId);
            // 帐套选择
            $('#zt_select').lrselect({
                type: 'default',
                //placeholder: '请选择帐套',
                // 展开最大高度
                maxHeight: 380,
                allowSearch: true
            });
            // 部门选择
            $('#departmentId').lrselect({
                type: 'multiple',
                placeholder: '部门',
                // 是否允许搜索
                allowSearch: true,
                select: function (item) {
                    if (item && item.value != '') {
                        departmentId = item.value;
                    } else {
                        departmentId = '';
                    }
                }
            });
            // 用户类型
            $('#userCategory').lrDataItemSelect({
                code: 'UserCategorys',
                type: 'multiple',
                placeholder: "员工类型",
                allowSearch: true
            });
            // 查询
            $('#btn_Search').on('click', function () {
                var keyword = $('#txt_Keyword').val();
                page.search({keyword: keyword});
            });
            // 刷新
            $('#lr_refresh').on('click', function () {
                learun.layerConfirm('是否确认删除账套内不存在的职工工资记录?', function (res) {
                    if (res) {
                        learun.postForm(config.base_server() + 'gzrecordsalarys/deleteNotInZtUser?companyId=' + companyId + '&ztId=' + ztId + '&month=' + month + '&access_token=' + config.getToken().access_token, {
                            companyId: companyId,
                            ztId: ztId,
                            month: month
                        }, function () {
                            //refreshGirdData();
                        });
                    }
                });
            });
            //执行计算
            $("#lr_calc").on('click', function () {
                learun.layerConfirm('是否确认重新计算工资?', function (res) {
                    if (res) {
                        learun.postForm(config.base_server() + 'gzrecordsalarys/calc?companyId=' + companyId + '&ztId=' + ztId + '&access_token=' + config.getToken().access_token, {
                            companyId: companyId,
                            ztId: ztId
                        }, function () {
                            refreshGirdData();
                        });
                    }
                });
            });
            //Excel导入
            $("#lr_import").on('click', function () {
                var userCategory = $('#userCategory').lrselectGet();
                learun.layerForm({
                    id: 'UploadifyForm_salary',
                    title: '上传文件',
                    url: config.webportal_server + 'pages/salary/recordSalary/uploadifyForm.html?companyId=' + companyId + '&ztId=' + ztId + '&category=' + encodeURI(encodeURI(userCategory)) + '&access_token=' + config.getToken().access_token,
                    width: 600,
                    height: 400,
                    callBack: function (id) {
                        return top[id].acceptClick(function (datas) {
                            if (datas) {
                                var index = top.layer.getFrameIndex("UploadifyForm_salary");
                                top.layer.close(index);
                                refreshGirdData();
                                if(datas.hasChange) {  //有人晋升
                                    needSetActionTimeUserids = datas.userids.join(',');
                                    learun.layerForm({
                                        id: 'setActionTime',
                                        title: '设置执行时间',
                                        btn: null,
                                        url: config.webportal_server + 'pages/system/user/setActionTime.html?access_token=' + config.getToken().access_token,
                                        width: 1366,
                                        height: 800,
                                    });
                                }
                            }
                        });
                    }
                });
            });
            //Excel导出
            $("#lr_export").on('click', function () {
                params.access_token = config.getToken().access_token;
                params.columns = null;
                learun.download({
                    url: config.base_server() + 'gzrecordsalarys/exportExcel',
                    param: params,
                    method: 'GET'
                });
            });
            //选择列导出
            $('#lr_export_select').on('click', function () {
                var ztId = $('#zt_select').lrselectGet();
                if (!ztId) {
                    learun.alert.warning('请选择账套！');
                    return false;
                }
                var month = $("#month").val();
                learun.layerForm({
                    id: 'form_printsetting',
                    title: '打印设置',
                    url: config.webportal_server + 'pages/salary/recordSalary/exportColumn.html?companyId=' + companyId + '&ztId=' + ztId + '&month=' + month + '&access_token=' + config.getToken().access_token,
                    width: 500,
                    height: 520,
                    callBack: function (id) {
                        var configData = top[id].acceptClick();
                        if (configData) {
                            var index = top.layer.getFrameIndex("form_printsetting");
                            top.layer.close(index);

                            params.access_token = config.getToken().access_token;
                            params.columns = configData.columns;
                            learun.download({
                                url: config.base_server() + 'gzrecordsalarys/exportExcel',
                                param: params,
                                method: 'GET'
                            });

                        }
                    }
                });
            });
            // 编辑
            $('#lr_edit').on('click', function () {
                learun.layerForm({
                    id: 'form',
                    title: '编辑',
                    url: config.webportal_server + 'pages/salary/recordSalary/edit.html?access_token=' + config.getToken().access_token + '&companyId=' + companyId + '&ztId=' + ztId,
                    width: 700,
                    height: 460,
                    callBack: function (id) {
                        return top[id].acceptClick(refreshGirdData);
                    }
                });

            });
            //保存
            $("#lr_save").on('click', function () {
                params.access_token = config.getToken().access_token;
                var productData = [];
                var productDataTmp = $('#gridtable').jfGridGet('rowdatas');
                for (var i = 0, l = productDataTmp.length; i < l; i++) {
                    jQuery.each(productDataTmp[i], function (key, val) {
                        var index = $.inArray(key, colNames);
                        if (index >= 0) {
                            var data = jQuery.extend({}, productDataTmp[i]);
                            data.itemId = key;
                            data.value = val;
                            data.companyId = companyId;
                            data.ztId = ztId;
                            productData.push(data);
                        }
                    });
                }

                var postData = productData;
                $.lrSaveForm(config.base_server() + 'gzrecordsalarys/saveOrUpdate2?companyId=' + companyId + '&ztId=' + ztId + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
                    if (res.resp_code == 200) {
                        refreshGirdData();
                    }
                });
            });

            //选列查看
            $('#lr_column').on('click', function () {
                var ztId = $('#zt_select').lrselectGet();
                if (!ztId) {
                    learun.alert.warning('请选择账套！');
                    return false;
                }
                var month = $("#month").val();
                learun.layerForm({
                    id: 'form_printsetting',
                    title: '选择款项查看',
                    url: config.webportal_server + 'pages/salary/recordSalary/exportColumn.html?companyId=' + companyId + '&ztId=' + ztId + '&month=' + month + '&access_token=' + config.getToken().access_token,
                    width: 500,
                    height: 520,
                    callBack: function (id) {
                        var configData = top[id].acceptClick();
                        if (configData) {
                            var index = top.layer.getFrameIndex("form_printsetting");
                            top.layer.close(index);

                            params.access_token = config.getToken().access_token;
                            params.columns = configData.columns;
                            selectColumns = configData.columns; //所选列

                            var _tempHeaderCols = jQuery.extend(true, [], headerCols);
                            for (var i = 0; i < _tempHeaderCols.length; i++) {
                                if ((_tempHeaderCols[i].name != 'id' && _tempHeaderCols[i].name != 'departmentname' && _tempHeaderCols[i].name != 'usercode' && _tempHeaderCols[i].name != 'username') &&
                                    configData.columns.indexOf(_tempHeaderCols[i].label) < 0
                                ) {
                                    _tempHeaderCols.splice(i, 1);
                                    i--;
                                }
                            }

                            page.initGrid(_tempHeaderCols);
                            page.search();
                        }
                    }
                });
            });

        },
        initGrid: function (headData) {
            $('#gridtable').jfGridClear();
            $('#gridtable').jfGrid({
                url: config.base_server() + 'gzrecordsalarys/list?access_token=' + config.getToken().access_token,
                headData: headData,
                isPage: false,
                isEdit: true,
                rows: 1000,
                reloadSelected: true,
                mainId: 'code',
                dblclick: function (row) {
                    var keyValue = $('#gridtable').jfGridValue('userid');
                    if (learun.checkrow(keyValue)) {
                        learun.layerForm({
                            id: 'form',
                            title: '工资录入',
                            url: config.webportal_server + 'pages/salary/recordSalary/form.html?companyId=' + companyId + '&ztId=' + ztId + '&keyValue=' + keyValue + '&access_token=' + config.getToken().access_token,
                            width: 900,
                            height: 760,
                            callBack: function (id) {
                                return top[id].acceptClick(refreshGirdData);
                            }
                        });
                    }
                },
            });
        },
        initHeader: function (param) {
            param = param || {};
            param.companyId = companyId;
            param.ztId = ztId;
            param.editable = "1";
            learun.httpPost2(config.base_server() + 'gzrecordsalarys/header?access_token=' + config.getToken().access_token, param, function (res) {
                learun.loading(false);
                if (res.resp_code == 200) {
                    colNames = res.data.colNames;
                    for (var i = 0; i < res.data.colData.length; i++) {
                        if (res.data.colData[i].formatter) {
                            res.data.colData[i].formatter = eval("(function(){return " + res.data.colData[i].formatter + " })()");
                        }
                        if (res.data.colData[i].edit && res.data.colData[i].edit.change) {
                            res.data.colData[i].edit.change = eval("(function(){return " + res.data.colData[i].edit.change + " })()");
                        }
                        if (res.data.colData[i].children) {
                            for (var j = 0; j < res.data.colData[i].children.length; j++) {
                                if (res.data.colData[i].children[j].formatter) {
                                    res.data.colData[i].children[j].formatter = eval("(function(){return " + res.data.colData[i].children[j].formatter + " })()");
                                }
                            }
                        }
                    }
                    headerCols = jQuery.extend(true, [], res.data.colData);
                    // page.initGrid(res.data.colData);
                } else {
                    learun.alert.error(res.resp_msg);
                    learun.httpErrorLog(res.resp_msg);
                }
            });

            learun.httpPost2(config.base_server() + 'gzenablemonths/findByZtId?companyId=' + companyId + '&ztId=' + ztId + '&access_token=' + config.getToken().access_token, {}, function (res) {
                learun.loading(false);
                if (res.resp_code == 200) {
                    month = res.data.currentMonth;
                    $("#lb_current").html("当前月份:" + res.data.currentMonth)
                }
            });
        },
        search: function (param) {
            var keyword = $('#txt_Keyword').val();
            param = param || {};
            param.companyId = companyId;
            param.ztId = ztId;
            param.keyword = keyword;

            var departmentId = $('#departmentId').lrselectGet();
            var userCategory = $('#userCategory').lrselectGet();
            param.departmentId = departmentId;
            param.userCategory = userCategory;

            params = param;

            $('#gridtable').jfGridSet('reload', param);
        }
    };

    // 保存数据后回调刷新
    refreshGirdData = function () {
        page.search();
    };

    page.init();
}


